﻿using System;
using System.Threading;

using SBPweb.PlAzureNet.Server.Library.Strategies;

namespace SBPweb.PlAzureNet.Server.Library.Processes
{

    public class LotteryThread : IDisposable
    {

        #region Fields

        private Thread thread;
        private static int i;

        #endregion

        #region Constructor logic

        public LotteryThread()
        {
            thread = new Thread(new ParameterizedThreadStart(OnStart));
            thread.Name = "LotteryThread#" + i++;
        }

        #endregion

        #region Methods
        
        public void Dispose()
        {
            thread.Abort();
        }

        public void Start(params object[] args)
        {
            thread.Start(args);
        }

        private void OnStart(object args)
        {
            object[] a = args as object[];
            if (a == null || a.Length < 1)
            {
                return;
            }
            long roundId = (long)a[0];

            Process(roundId);

            if (a.Length > 1)
            {
                Action<long> endAction = a[1] as Action<long>;
                if (endAction != null)
                {
                    endAction(roundId);
                }
            }

            Dispose();
        }

        protected virtual void Process(long roundId)
        {
            Console.WriteLine("\t\tLottery thread '{0}' started.", thread.Name);

            ActionResultsGenerator.CloseRound(roundId);

            Console.WriteLine("\t\tLottery thread '{0}' stopped.", thread.Name);
        }

        #endregion

    }

}